// 阿里云oss web 直传，优点 web 断 object 直接上传到 阿里云oss ，不经过闪广服务器端，节省流量，还可保证上传速度。
// 详细文档地址 服务端签名直传并设置上传回调 https://help.aliyun.com/document_detail/31927.html?spm=5176.doc31926.6.630.aVSm0V
accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000;

function send_request()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlhttp!=null)
    {
        serverUrl = '/article/ossini'
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText
    }
    else
    {
        ////alert("Your browser does not support XMLHTTP.");
    }
};

function check_object_radio() {
    var tt = document.getElementsByName('myradio');
    for (var i = 0; i < tt.length ; i++ )
    {
        if(tt[i].checked)
        {
            g_object_name_type = tt[i].value;
            break;
        }
    }
}

function get_signature()
{
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse(new Date()) / 1000;
    if (expire < now + 3)
    {
        body = send_request()
        var obj = eval ("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback']
        key = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name')
    {
        suffix = get_suffix(filename)
        g_object_name = key + random_string(10) + suffix
    }
    return ''
}

function get_uploaded_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if(g_object_name_type == 'random_name')
    {
        return g_object_name
    }
}

function set_upload_param(up, filename, ret,content_type)
{
    if (ret == false)
    {
        ret = get_signature()
    }
    g_object_name = key;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }

    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'callback' : callbackbody,
        'signature': signature,
        "x:type":content_type, // 自定义参数区分内容类型  desc :https://helpcdn.aliyun.com/document_detail/31989.html
        "x:article_id":$article_id, // 自定义参数区分内容类型  desc :https://helpcdn.aliyun.com/document_detail/31989.html
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

/**
 * 选择图片
 * @type {Uploader}
 */
var uploaderImg = new plupload.Uploader({
    runtimes : 'html5,flash,silverlight,html4',
    browse_button : 'select-img',
    multi_selection: true,
    container: document.getElementById('container-img'),
    flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
    url : 'http://oss.aliyuncs.com',

    filters: {
        mime_types : [ //只允许上传图片和zip,rar文件
            // { title : "Image files", extensions : $allowed_image_type },  // 加了之后手机上有些图片（照片）无法上传
        ],
        max_file_size : $allowed_image_size, //最大只能上传10mb的文件
        prevent_duplicates : false //允许选取重复文件
    },

    init: {
        PostInit: function() {
            //alert(1);
            document.getElementById('post-img').onclick = function() {
                
                set_upload_param(uploaderImg, '', false,'image');
                return false;
            };
        },

        FilesAdded: function(up, files) {
            //alert(2);
            plupload.each(files, function(file) {
                document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
                    +'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
                    +'</div>';
                ////alert(22);
                $('#post-img').click(); // 发送oss请求
            });
        },

        BeforeUpload: function(up, file) {
            //alert(3);
            check_object_radio();
            set_upload_param(up, file.name, true,'image');
        },

        UploadProgress: function(up, file) {
            var d = document.getElementById(file.id);
            d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            var prog = d.getElementsByTagName('div')[0];
            var progBar = prog.getElementsByTagName('div')[0]
            progBar.style.width= 2*file.percent+'px';
            progBar.setAttribute('aria-valuenow', file.percent);
        },

        FileUploaded: function(up, file, info) {
            //alert(5);
            if (info.status == 200)
            {
                var res_data = $.parseJSON(info.response);
                if (res_data) {
                    var item_id = res_data.CallInfo.id;
                    var img_ele = '' +
                        '<div class="posre margin-adjust"  id="item['+item_id+']" item_id="'+item_id+'">' +
                        '   <img class="img-width" src="'+$oss_url_path+'/'+get_uploaded_object_name(file.name)+'" id="imgbianji"/>' +
                        '   <div class="publish-bianji">' +
                        '       <div class="four1 four" onclick=""><div class="addImg uploadImg"><a href="javascript:void(0);" class="btn" style="color:white"><img src="/img/imgup.png" class="img-middle img-padding1" style="width: 16px;"/>图片</a>' +
                        '       <a href="javascript:void(0);" class="btn"></a></div></div><div class="flt bianji-bar"></div><div class="four2 four publishDel"><img src="/img/delete.png" class="img-sub img-padding1" style="width: 13px;"/>删除</div>' +
                        '   </div>';
                    '</div>';

                    $(".content").append(img_ele);
                }
            }
            else
            {
                ////alert('上传文件出错：'+info.response);
            }
        },

        Error: function(up, err) {
            ////alert(6);
            if (err.code == -600) {
                ////alert("对不起，选择的文件太大了");
            }
            else if (err.code == -601) {
                ////alert("对不起，暂不支持此种类型文件上传");
            }
            else if (err.code == -602) {
                ////alert("\n对不起，这个文件已经上传过一遍了");
            }
            else
            {
                ////alert("\nError xml:" + err.response);
            }
        }
    }
});
uploaderImg.init();
//alert(0);

/**
 * 选择视频
 * @type {Uploader}
 */
var uploaderVideo = new plupload.Uploader({
    runtimes : 'html5,flash,silverlight,html4',
    browse_button : 'select-video',
    multi_selection: true,
    container: document.getElementById('container-video'),
    flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
    url : 'http://oss.aliyuncs.com',
    filters: {
        mime_types : [ //只允许上传图片和zip,rar文件
            { title : "Video", extensions : $allowed_video_type }
        ],
        max_file_size : $allowed_video_size, //最大只能上传10mb的文件
        prevent_duplicates : false //允许选取重复文件
    },

    init: {
        PostInit: function() {
            document.getElementById('post-video').onclick = function() {
                // console.log('-video');
                set_upload_param(uploaderVideo, '', false, 'video');
                return false;
            };
        },

        FilesAdded: function(up, files) {
            plupload.each(files, function(file) {
                document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
                    +'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
                    +'</div>';
                $('#post-video').click();// 发送oss请求
            });

        },

        BeforeUpload: function(up, file) {
            check_object_radio();
            set_upload_param(up, file.name, true, 'video');
        },

        UploadProgress: function(up, file) {
            var d = document.getElementById(file.id);
            d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            var prog = d.getElementsByTagName('div')[0];
            var progBar = prog.getElementsByTagName('div')[0]
            progBar.style.width= 2*file.percent+'px';
            progBar.setAttribute('aria-valuenow', file.percent);
        },

        FileUploaded: function(up, file, info) {
            if (info.status == 200)
            {
                var res_data = $.parseJSON(info.response);
                if (res_data) {
                    var item_id = res_data.CallInfo.id;
                    var vidoe_ele = '<div class="posre img-width margin-adjust"  id="item['+item_id+']" item_id="'+item_id+'">' +
                        '<img src="/img/playicon.png" class="playicon"/>' +
                        '<video class="img-width my_video_1 pause" preload="auto" data-setup="{}">' +
                        '   <source src="' + $oss_url_path + '/' + get_uploaded_object_name(file.name) + '" type="audio/mp4">' +
                        '</video>' +
                        '<div class="publish-bianji">' +
                        '   <div class="four1 four" onclick=""><div class="addImg uploadImg"><a href="javascript:void(0);" class="btn" style="color:white"><img src="/img/videoup.png" class="img-middle img-padding1" style="width: 16px;"/>视频</a>' +
                        '   <a href="javascript:void(0);" class="btn"></a></div></div><div class="flt bianji-bar"></div><div class="four2 four publishDel"><img src="/img/delete.png" class="img-sub img-padding1" style="width: 13px;"/>删除</div>' +
                        '</div>' +
                        '</div>';
                    $(".content").append(vidoe_ele);// 文章内追加内容
                }
            }
            else
            {
                ////alert('上传文件出错：'+info.response);
            }
        },

        Error: function(up, err) {
            if (err.code == -600) {
                ////alert("对不起，选择的文件太大了");
            }
            else if (err.code == -601) {
                ////alert("对不起，暂不支持此种类型文件上传");
            }
            else if (err.code == -602) {
                ////alert("\n对不起，这个文件已经上传过一遍了");
            }
            else
            {
                ////alert("\nError xml:" + err.response);
            }
        }
    }
});
uploaderVideo.init();

/**
 * 选择音频
 * @type {Uploader}
 */
var uploaderAudio = new plupload.Uploader({
    runtimes : 'html5,flash,silverlight,html4',
    browse_button : 'select-audio',
    multi_selection: true,
    container: document.getElementById('container-audio'),
    flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
    url : 'http://oss.aliyuncs.com',
    filters: {
        mime_types : [ //只允许上传图片和zip,rar文件
            { title : "Audio", extensions : $allowed_audio_type }
        ],
        max_file_size : $allowed_audio_size, //最大只能上传10mb的文件
        prevent_duplicates : false //允许选取重复文件
    },

    init: {
        PostInit: function() {
            document.getElementById('post-audio').onclick = function() {
                //console.log('-audio');
                set_upload_param(uploaderAudio, '', false, 'audio');
                return false;
            };
        },

        FilesAdded: function(up, files) {
            plupload.each(files, function(file) {
                document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
                    +'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
                    +'</div>';
                $('#post-audio').click();// 发送oss请求
            });
        },

        BeforeUpload: function(up, file) {
            //console.log(file);
            check_object_radio();
            set_upload_param(up, file.name, true, 'audio');
        },

        UploadProgress: function(up, file) {
            var d = document.getElementById(file.id);
            d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            var prog = d.getElementsByTagName('div')[0];
            var progBar = prog.getElementsByTagName('div')[0]
            progBar.style.width= 2*file.percent+'px';
            progBar.setAttribute('aria-valuenow', file.percent);
        },

        FileUploaded: function(up, file, info) {
            if (info.status == 200)
            {
                var res_data = $.parseJSON(info.response);
                if (res_data) {
                    var item_id = res_data.CallInfo.id;
                    var audio_ele = '<div class="posre margin-adjust"  id="item['+item_id+']" item_id="'+item_id+'">'+
					                    '<audio controls="controls" class="img-width"><source src="' + $oss_url_path + '/' + get_uploaded_object_name(file.name) + '" type="audio/mpeg"></audio>'+
					                    '<div class="publish-bianji">' +
						                    '<div class="four1 four" onclick=""><div class="addImg uploadImg"><a href="javascript:void(0);" class="btn" style="color:white"><img src="/img/audioup.png" class="img-middle img-padding1" style="width: 16px;"/>音频</a><a href="javascript:void(0);" class="btn"></a></div></div><div class="flt bianji-bar"></div><div class="four2 four publishDel"><img src="/img/delete.png" class="img-sub img-padding1" style="width: 13px;"/>删除</div>' +
						                '</div>';
					                '</div>';
                    $(".content").append(audio_ele);// 文章内追加内容
                }
            }
            else
            {
                ////alert('上传文件出错：'+info.response);
                // //console.log(response);
                // document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
            }
        },

        Error: function(up, err) {
            if (err.code == -600) {
                ////alert("对不起，选择的文件太大了");
            }
            else if (err.code == -601) {
                ////alert("对不起，暂不支持此种类型文件上传");
            }
            else if (err.code == -602) {
                ////alert("\n对不起，这个文件已经上传过一遍了");
            }
            else
            {
                ////alert("\nError xml:" + err.response);
            }
        }
    }
});
uploaderAudio.init();